//引用地址配置
var config = require("url_config.js");

module.exports = {
  fetchData: fetchData,
  getUrl: getUrl,
}

/**
 * 获取数据
 */
function fetchData(url, data, cb, method = "POST", forceCallBack = false) {
  data["version"] = getApp().globalData.version;
  data['appid'] = getApp().globalData.app_id;
  data['from'] = "wechat";
  data['miniproid'] = getApp().globalData.miniproid
  data['uniq_openid'] = getApp().globalData.uniq_openid
  if (url == getApp().globalData.API_Base_URL + '/uri/user/getOpenid' || url == getApp().globalData.API_Base_URL +'/uri/user/getUserInfo'){
    data['real_openid']=''
  }else{
    console.log(getApp().globalData.real_openid)
    data['real_openid'] = wx.getStorageSync('real_openid') 
    data['pay_way'] = 'wechat'
    data['unionid'] = getApp().globalData.unionid
    console.log(url)
  } if (url.indexOf('guanwan.henghi') == -1) {
    data['token'] = wx.getStorageSync('token__')
  }
  data['token_key'] = wx.getStorageSync('token_key')
  console.log(getApp().globalData)
  //组建请求
  var post_obj = {
    url: url,
    data: data,
    method: method,
    success: res => {
      if (method == "POST") {
        console.log("POST请求成功返回", url, data, res);
      }
      else {
        console.log("GET请求成功返回", url, data, res);
      }
      //网络接口正常运作的情况
      if (res.statusCode == 200) {
        //强制回调
        if (forceCallBack) {
          cb(res);
          return;
        }
        //接口返回提示错误
        if (res.data.code != 0) {
          //先隐藏加载窗口
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false,
            success: res => { }
          })
          return;
        }
        //接口正常返回
        if (cb && typeof cb == "function") {
          cb(res);
        } else {
          return res;
        }

      } else {
        wx.showModal({
          title: '提示',
          content: '网络接口繁忙，请稍候再试',
          showCancel: false,
          success: res => { }
        })
      }
    },
    fail: res => {
      console.log("请求失败返回", url, data, res);
      return false;
    }
  }

  //post请求，要发送header
  if (method == "POST") {
    post_obj["header"] = {
      "content-type": "application/x-www-form-urlencoded",
    };
  }

  wx.getNetworkType({
    success: res => {
      var networkType = res.networkType
      if (networkType == "none" || networkType == "unknown") {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '请检查网络',
          showCancel: false,
          success: res => {

          }
        })
      }
    }
  })


  //发送网络请求
  wx.request(post_obj);
}

/**
 * 根据名称获取不同的URL地址
 */
function getUrl(name) {
  console.log(name)
  for (var i = 0; i < config.URL_CONFIG.length; i++) {
    var item = config.URL_CONFIG[i];
    if (item.key == name) {
      return item.url;
    }
  }
}